<?php

namespace App\Http\Controllers\api;

use App\Models\Book;
use Illuminate\Support\Facades\Input;
use App\Models\Section;
use App\Models\Operation;
use App\Models\Member;
use App\Models\Comment;

class SectionController extends BaseController {
	
	public function store() {
		$input = Input::all();
		$book = Book::where('name', $input['book_name'])->first();
		if(!is_null($book)) {
			unset($input['book_name']);
			$input['book_id'] = $book->id;
			$section = Section::where('book_id', $input['book_id'])
					->where('name', $input['name'])->first();
			if(is_null($section)) {
				Section::create($input);
				Operation::create([
					'action' => '添加章节',
					'content' => '《'. $book->name.'》 - '.$input['name']
				]);
				return 200;
			}
			Operation::create([
				'action' => '添加章节失败',
				'content' => '章节已存在：《'.$section->book->name.'》->'.$input['name']
			]);
			
			return -1;
		}
		Operation::create([
			'action' => '添加章节失败',
			'content' => '没有该书籍：'.$input['book_name']
		]);
		
		return -1;
	}
	
	public function comment($sectionId) {
		$memberId = Input::get('member_id');
		$member = Member::find($memberId);
		$section = Section::find($sectionId);
		$content = Input::get('content');
		if(is_null($section) or is_null($member) or is_null($content)) {
			return -1;
		}
		$comment = Comment::create([
			'member_id' => $member->id,
			'book_id' => $section->book_id,
			'section_id' => $section->id,
			'content' => $content
		]);
		if(is_null($comment)) {
			return -1;
		}
		$data = [
			'avatarUrl' => $comment->member->avatarUrl(),
			'content' => $comment->content,
			'created_at' => $comment->created_at->format('Y-m-d h:i')
		];
		return $data;
	}
}
